<template>
  <div>
    <el-row :gutter="20" class="search-row">
      <el-col :span="6">
        <label style="font-weight: bold;">请输入用户名</label>
      </el-col>
      <el-col :span="10">
        <el-input v-model="searchName" placeholder="输入用户名进行搜索" clearable @clear="handleClear"/>
      </el-col>
      <el-col :span="8">
        <el-button type="danger" @click="loadUserList()" round>搜索</el-button>
        <el-button type="primary" @click="showAddDialog" round>添加用户</el-button>
      </el-col>
    </el-row>


    <!-- 添加用户对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加用户" label-width="auto">
      <el-form :model="addForm">
        <el-form-item label="用户名">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addUser">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户" label-width="auto" style="max-width: 600px">
      <el-form :model="editForm">
        <el-form-item label="用户头像">
              <img v-if="editForm.avatar" :src="editForm.avatar"  >
        </el-form-item>
        <el-form-item label="用户编号">
          <el-input v-model="editForm.uid" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户名 ">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="editForm.password" type="password"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateUser">确定</el-button>
      </template>
    </el-dialog>

    <el-table :data="userlist" stripe border show-overflow-tooltip table-layout="fixed" :empty-text="defaultempty">
      <el-table-column prop="id" label="用户编号"></el-table-column>
      <el-table-column prop="avatar" label="头像" align="center">
        <template #default="scope">
          <img :src="scope.row.avatar" alt="" style="height: 50px">
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="password" label="密码"></el-table-column>
      <el-table-column prop="createTime" label="创建时间">
        <template #default="scope">
          {{ formatTimestamp(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column align="right" label="操作" width="150">
        <template #default="scope">
          <el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteRow(scope.$index,scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.page"
        :page-sizes="[5, 10, 20]"
        :page-size="pagination.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total">
    </el-pagination>
  </div>
</template>

<script>
import axios from 'axios'
import {useUserInfoStore} from "../pinia/userinfo"
import {UserControllerService} from "../../api/index.js";
import {ElMessage} from "element-plus";
import {formatTimestamp} from "../util/TimeUtil.js";
import { watch } from 'vue';

export default {
  data() {
    return {
      userlist: [],
      searchName: '',
      sprheaders: {
        username: "",
        token: ""
      },
      defaultempty:'当前无数据',
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        avatar: '',
        username: '',
        password: '',
      },
      editForm: {
        uid: '',
        avatar: '',
        username: '',
        password: '',
      },
      pagination: {
        page: 1,  // 当前页码
        limit: 10, // 每页行数
        total: 0   // 总记录数
      }
    }
  },
  created() {
    const userStore = useUserInfoStore();
    this.sprheaders.username = userStore.getUsername
    this.sprheaders.token = userStore.getToken
    this.loadUserList()
  },
  methods: {
    formatTimestamp,
    async loadUserList() {
      const res = await UserControllerService.getUserByPage(
          this.searchName,
          this.pagination.page,
          this.pagination.limit
      )
      if (res.code === 0) {
        this.userlist = res.data
        this.pagination.total = res.count
      } else {
        ElMessage.error(res)
        defaultempty=res.msg
      }
    },
    handleSizeChange(val) {
      this.pagination.limit = val
      this.loadUserList()
    },
    handleCurrentChange(val) {
      this.pagination.page = val
      this.loadUserList()
    },
    showAddDialog() {
      this.addDialogVisible = true
      this.addForm = {
        username: '',
        password: '',
      }
    },
    showEditDialog(row) {
      this.editDialogVisible = true
      this.editForm = {
        uid: row.id,
        avatar: row.avatar,
        username: row.username,
        password: row.password
      }
    },
    async addUser() {
      const res = await UserControllerService.addUser(
          {
            avatar: 'https://picsum.photos/200',
            username: this.addForm.username,
            password: this.addForm.password
          }
      )
      console.log(res)
      if (res.code === 0) {
        ElMessage.success("数据添加成功！")
        this.addDialogVisible=false
        this.loadUserList()
      } else {
        ElMessage.error(res.msg)
      }
    },
    async updateUser() {
        try {
            const res = await UserControllerService.updateUser({
                id: this.editForm.uid,
                avatar: this.editForm.avatar,
                username: this.editForm.username,
                password: this.editForm.password
            });
            if (res.code === 0) {
                ElMessage.success('更新成功');
                this.editDialogVisible = false;
                this.loadUserList();
            } else {
                ElMessage.error(res.msg);
            }
        } catch (error) {
            ElMessage.error('网络错误');
        }
    },
    async deleteRow(index, row) {
        this.$confirm('确认删除该用户吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => {
            try {
                const res = await UserControllerService.deleteUser(row.id);
                if (res.code === 0) {
                    ElMessage.success('删除成功');
                    this.loadUserList();
                } else {
                    ElMessage.error(res.msg);
                }
            } catch (error) {
                ElMessage.error('网络错误');
            }
        }).catch(() => {
            this.$message.info('已取消删除');
        });
    },
    handleClear() {
      this.loadUserList()
    }
  }
}
</script>
<style scoped>
.search-row {
  margin-bottom: 20px;
}

.el-button {
  margin-left: 10px;
}

</style>
